<template>
  <div class="min-h-screen bg-gray-50 dark:bg-gray-900 p-6">
    <div class="max-w-6xl mx-auto">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900 dark:text-white">
          技能管理
        </h1>
        <p class="text-gray-600 dark:text-gray-400 mt-2">
          管理技能分类和技能项
        </p>
      </div>

      <!-- 技能分类管理 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-6">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white">
            技能分类
          </h2>
          <button
            @click="openCategoryModal()"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            添加分类
          </button>
        </div>

        <!-- 分类列表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="category in categories"
            :key="category.id"
            class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow dark:bg-gray-700"
          >
            <div class="flex items-center mb-3">
              <div
                class="w-8 h-8 rounded-md mr-3 flex items-center justify-center"
                :style="{ backgroundColor: category.color }"
              >
                <Icon :name="category.icon" class="text-white text-sm" />
              </div>
              <h3 class="font-medium text-gray-900 dark:text-white">
                {{ category.name }}
              </h3>
            </div>
            <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">
              {{ category.description }}
            </p>
            <div class="flex space-x-2">
              <button
                @click="editCategory(category)"
                class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-sm"
              >
                编辑
              </button>
              <button
                @click="deleteCategory(category.id)"
                class="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 text-sm"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 技能项管理 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white">
            技能项
          </h2>
          <button
            @click="openSkillModal()"
            class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors"
          >
            添加技能
          </button>
        </div>

        <!-- 技能列表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div
            v-for="skill in skills"
            :key="skill.id"
            class="border border-gray-200 dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow dark:bg-gray-700"
          >
            <div class="flex justify-between items-start mb-3">
              <span
                class="px-3 py-1 rounded-full text-sm font-medium"
                :style="{
                  backgroundColor: skill.color + '20',
                  color: skill.color,
                }"
              >
                {{ skill.name }}
              </span>
              <span class="text-xs text-gray-500 dark:text-gray-400">{{
                getCategoryName(skill.category_id)
              }}</span>
            </div>
            <p class="text-sm text-gray-600 dark:text-gray-400 mb-3">
              {{ skill.description }}
            </p>
            <div class="flex justify-end space-x-2">
              <button
                @click="editSkill(skill)"
                class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-sm"
              >
                编辑
              </button>
              <button
                @click="deleteSkill(skill.id)"
                class="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 text-sm"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分类编辑模态框 -->
    <div
      v-if="showCategoryModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
    >
      <div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4 text-gray-900 dark:text-white">
          {{ editingCategory ? "编辑分类" : "添加分类" }}
        </h3>
        <form @submit.prevent="saveCategory" class="space-y-4">
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >分类名称 *</label
            >
            <input
              v-model="categoryForm.name"
              type="text"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              required
            />
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >描述</label
            >
            <textarea
              v-model="categoryForm.description"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              rows="2"
              placeholder="分类描述..."
            ></textarea>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >颜色</label
            >
            <div class="flex items-center space-x-3">
              <input
                v-model="categoryForm.color"
                type="color"
                class="w-12 h-10 border rounded-md dark:bg-gray-700 dark:border-gray-600"
              />
              <span class="text-sm text-gray-500 dark:text-gray-400">{{
                categoryForm.color
              }}</span>
            </div>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >图标</label
            >
            <input
              v-model="categoryForm.icon"
              type="text"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              placeholder="例如：fa:code"
            />
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
              使用 Font Awesome 图标格式，如：fa:code, fa:server, fa:cogs
            </p>
          </div>
          <div class="flex justify-end space-x-3">
            <button
              type="button"
              @click="closeCategoryModal"
              class="px-4 py-2 border rounded-md hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700"
            >
              取消
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
              :disabled="loading"
            >
              {{ loading ? "保存中..." : "保存" }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 技能编辑模态框 -->
    <div
      v-if="showSkillModal"
      class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
    >
      <div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-md">
        <h3 class="text-lg font-semibold mb-4 text-gray-900 dark:text-white">
          {{ editingSkill ? "编辑技能" : "添加技能" }}
        </h3>
        <form @submit.prevent="saveSkill" class="space-y-4">
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >技能名称 *</label
            >
            <input
              v-model="skillForm.name"
              type="text"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              required
            />
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >描述</label
            >
            <textarea
              v-model="skillForm.description"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              rows="2"
              placeholder="技能描述..."
            ></textarea>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >分类 *</label
            >
            <select
              v-model="skillForm.category_id"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
              required
            >
              <option value="">请选择分类</option>
              <option v-for="cat in categories" :key="cat.id" :value="cat.id">
                {{ cat.name }}
              </option>
            </select>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >技能等级</label
            >
            <select
              v-model="skillForm.level"
              class="w-full px-3 py-2 border rounded-md dark:bg-gray-700 dark:border-gray-600 dark:text-white"
            >
              <option value="beginner">初级</option>
              <option value="intermediate">中级</option>
              <option value="advanced">高级</option>
              <option value="expert">专家</option>
            </select>
          </div>
          <div>
            <label
              class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
              >颜色</label
            >
            <div class="flex items-center space-x-3">
              <input
                v-model="skillForm.color"
                type="color"
                class="w-12 h-10 border rounded-md dark:bg-gray-700 dark:border-gray-600"
              />
              <span class="text-sm text-gray-500 dark:text-gray-400">{{
                skillForm.color
              }}</span>
            </div>
          </div>

          <div class="flex justify-end space-x-3">
            <button
              type="button"
              @click="closeSkillModal"
              class="px-4 py-2 border rounded-md hover:bg-gray-50 dark:border-gray-600 dark:hover:bg-gray-700"
            >
              取消
            </button>
            <button
              type="submit"
              class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
              :disabled="loading"
            >
              {{ loading ? "保存中..." : "保存" }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
const categories = ref([]);
const skills = ref([]);
const showCategoryModal = ref(false);
const showSkillModal = ref(false);
const editingCategory = ref(null);
const editingSkill = ref(null);
const loading = ref(false);

const categoryForm = ref({
  name: "",
  description: "",
  color: "#3b82f6",
  icon: "fa:code",
});

const skillForm = ref({
  name: "",
  description: "",
  category_id: "",
  level: "intermediate",
  color: "#3b82f6",
});

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.value.find((cat) => cat.id === categoryId);
  return category ? category.name : "未知分类";
};

// 获取数据
const fetchData = async () => {
  try {
    const [skillsResult, categoriesResult] = await Promise.all([
      $fetch("/api/admin/skills"),
      $fetch("/api/skill-categories"),
    ]);

    if (skillsResult.success) {
      skills.value = skillsResult.data || [];
      // 确保技能数据中有 color 字段
      skills.value.forEach((skill) => {
        if (!skill.color) skill.color = "#3b82f6";
      });
    }
    if (categoriesResult.success)
      categories.value = categoriesResult.data || [];
  } catch (error) {
    ElMessage.error({
      message: "获取数据失败",
      type: "error",
      duration: 3000,
    });
    console.error("获取数据失败:", error);
  }
};

// 分类操作
const openCategoryModal = (category = null) => {
  editingCategory.value = category;
  if (category) {
    categoryForm.value = { ...category };
  } else {
    categoryForm.value = {
      name: "",
      description: "",
      color: "#3b82f6",
      icon: "fa:code",
    };
  }
  showCategoryModal.value = true;
};

const closeCategoryModal = () => {
  showCategoryModal.value = false;
  editingCategory.value = null;
};

const editCategory = (category) => {
  openCategoryModal(category);
};

const saveCategory = async () => {
  if (!categoryForm.value.name) {
    ElMessage.warning({
      message: "分类名称不能为空",
      type: "error",
      duration: 3000,
    });
    return;
  }

  loading.value = true;

  try {
    if (editingCategory.value) {
      // 更新分类
      const { success, message } = await $fetch(
        `/api/skill-categories/${editingCategory.value.id}`,
        {
          method: "PUT",
          body: categoryForm.value,
        }
      );

      if (success) {
        ElMessage.success({
          message: "分类更新成功",
          type: "success",
          duration: 3000,
        });
        closeCategoryModal();
        await fetchData();
      } else {
        ElMessage.error({
          message: message || "分类更新失败",
          type: "error",
          duration: 3000,
        });
      }
    } else {
      // 创建分类
      const { success, message } = await $fetch("/api/skill-categories", {
        method: "POST",
        body: categoryForm.value,
      });

      if (success) {
        ElMessage.success({
          message: "分类创建成功",
          type: "success",
          duration: 3000,
        });
        closeCategoryModal();
        await fetchData();
      } else {
        ElMessage.error({
          message: message || "分类创建失败",
          type: "error",
          duration: 3000,
        });
      }
    }
  } catch (error) {
    console.error("保存分类失败:", error);
    ElMessage.error({
      message: `保存分类失败: ${error.data?.message || error.message}`,
      type: "error",
      duration: 3000,
    });
  } finally {
    loading.value = false;
  }
};

const deleteCategory = async (id) => {
  if (!confirm("确定要删除这个分类吗？这将删除该分类下的所有技能！")) {
    return;
  }

  try {
    const { success,message } = await $fetch(`/api/skill-categories/${id}`, {
      method: "DELETE",
    });

    if (success) {
      ElMessage.success({
        message: "分类删除成功",
        type: "success",
        duration: 3000,
      });
      await fetchData();
    } else {
      ElMessage.error({
        message: message || "分类删除失败",
        type: "error",
        duration: 3000,
      });
    }
  } catch (error) {
    console.error("删除分类失败:", error);
    ElMessage.error({
      message: `删除分类失败: ${error.data?.message || error.message}`,
      type: "error",
      duration: 3000,
    });
  }
};

// 技能操作
const openSkillModal = (skill = null) => {
  editingSkill.value = skill;
  if (skill) {
    skillForm.value = {
      ...skill,
      category_id: skill.category_id.toString(),
    };
  } else {
    skillForm.value = {
      name: "",
      description: "",
      category_id: "",
      level: "intermediate",
      color: "#3b82f6",
    };
  }
  showSkillModal.value = true;
};

const closeSkillModal = () => {
  showSkillModal.value = false;
  editingSkill.value = null;
};

const editSkill = (skill) => {
  openSkillModal(skill);
};

const saveSkill = async () => {
  if (!skillForm.value.name) {
    ElMessage.warning({
      message: "技能名称不能为空",
      type: "error",
      duration: 3000,
    });
    return;
  }

  if (!skillForm.value.category_id) {
    ElMessage.warning({
      message: "请选择技能分类",
      type: "error",
      duration: 3000,
    });
    return;
  }

  loading.value = true;

  try {
    const formData = {
      ...skillForm.value,
      category_id: parseInt(skillForm.value.category_id),
    };

    if (editingSkill.value) {
      // 更新技能
      const { success,message } = await $fetch(`/api/skills/${editingSkill.value.id}`, {
        method: "PUT",
        body: formData,
      });

      if (success) {
        ElMessage.success({
          message: "技能更新成功",
          type: "success",
          duration: 3000,
        });
        closeSkillModal();
        await fetchData();
      } else {
        ElMessage.error({
          message: message || "技能更新失败",
          type: "error",
          duration: 3000,
        });
      }
    } else {
      // 创建技能
      const { success, message } = await $fetch("/api/skills", {
        method: "POST",
        body: formData,
      });

      if (success) {
        ElMessage.success({
          message: "技能创建成功",
          type: "success",
          duration: 3000,
        });
        closeSkillModal();
        await fetchData();
      } else {
        ElMessage.error({
          message: message || "技能创建失败",
          type: "error",
          duration: 3000,
        });
      }
    }
  } catch (error) {
    console.error("保存技能失败:", error);
    ElMessage.error({
      message: `保存技能失败: ${error.data?.message || error.message}`,
      type: "error",
      duration: 3000,
    });
  } finally {
    loading.value = false;
  }
};

const deleteSkill = async (id) => {
  if (!confirm("确定要删除这个技能吗？")) {
    return;
  }

  try {
    const { success, message } = await $fetch(`/api/skills/${id}`, {
      method: "DELETE",
    });

    if (success) {
      ElMessage.success({
        message: "技能删除成功",
        type: "success",
        duration: 3000,
      });
      await fetchData();
    } else {
      ElMessage.error({
        message: message || "技能删除失败",
        type: "error",
        duration: 3000,
      });
    }
  } catch (error) {
    console.error("删除技能失败:", error);
    ElMessage.error({
      message: `删除技能失败: ${error.data?.message || error.message}`,
      type: "error",
      duration: 3000,
    });
  }
};

// 页面加载时获取数据
onMounted(async () => {
  console.log("页面加载，开始获取数据...");
  await fetchData();
  console.log(
    "数据获取完成，技能数量:",
    skills.value.length,
    "分类数量:",
    categories.value.length
  );
});
</script>
